package cn.iocoder.yudao.module.crm.service.course;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.enums.Const;
import cn.iocoder.yudao.module.crm.dal.dataobject.coursematerialrlt.CourseMaterialRltDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.coursepackage.CoursePackageDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.coursepackagerlt.CoursePackageRltDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.subject.SubjectDO;
import cn.iocoder.yudao.module.crm.dal.mysql.coursematerialrlt.CourseMaterialRltMapper;
import cn.iocoder.yudao.module.crm.dal.mysql.coursepackage.CoursePackageMapper;
import cn.iocoder.yudao.module.system.enums.CommonConstants;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.crm.controller.admin.course.vo.*;
import cn.iocoder.yudao.module.crm.dal.dataobject.course.CourseDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.crm.dal.mysql.course.CourseMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.module.crm.enums.ErrorCodeConstants.*;

/**
 * 课程 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class CourseServiceImpl implements CourseService {

    @Resource
    private CourseMapper courseMapper;
    @Resource
    private CoursePackageMapper coursePackageMapper;
    @Resource
    private CourseMaterialRltMapper courseMaterialRltMapper;

    @Override
    public Long createCourse(CourseSaveReqVO createReqVO) {
        if(createReqVO.getParentId() != null && createReqVO.getParentId() > 0) {
            createReqVO.setParentId(createReqVO.getParentId());
        }else{
            createReqVO.setParentId(CommonConstants.ROOT_ID);
        }
        // 插入
        CourseDO course = BeanUtils.toBean(createReqVO, CourseDO.class);
        courseMapper.insert(course);
        // 返回
        return course.getId();
    }

    @Override
    public void updateCourse(CourseSaveReqVO updateReqVO) {
        // 校验存在
        validateCourseExists(updateReqVO.getId());
        // 更新
        CourseDO updateObj = BeanUtils.toBean(updateReqVO, CourseDO.class);
        courseMapper.updateById(updateObj);
    }

    @Override
    public void deleteCourse(Long id) {
        // 校验存在
        validateCourseExists(id);
        // 删除
        courseMapper.deleteById(id);
    }

    private void validateCourseExists(Long id) {
        if (courseMapper.selectById(id) == null) {
            throw exception(COURSE_NOT_EXISTS);
        }
    }

    @Override
    public CourseDO getCourse(Long id) {
        return courseMapper.selectById(id);
    }

    @Override
    public PageResult<CourseDO> getCoursePage(CoursePageReqVO pageReqVO) {
        // 查询套餐下课程
        if (pageReqVO.getCoursePackageId() != null && pageReqVO.getCoursePackageId() > 0) {
            if (!setCourseIdsFromPackage(pageReqVO, pageReqVO.getCoursePackageId(), true)) {
                return new PageResult<>(Collections.emptyList(), 0L);
            }
        }
        // 查询套餐没有的课程
        if (pageReqVO.getNotInCoursePackageId() != null && pageReqVO.getNotInCoursePackageId() > 0) {
            setCourseIdsFromPackage(pageReqVO, pageReqVO.getNotInCoursePackageId(), false);
        }
        return courseMapper.selectPage(pageReqVO);
    }

    /**
     * 从课程套餐中提取课程ID，并设置到 pageReqVO 中
     *
     * @param pageReqVO       请求参数对象
     * @param packageId       套餐ID
     * @param isInCourseIds   是否是设置 inCourseIds
     * @return 如果成功设置课程ID返回 true，否则返回 false
     */
    private boolean setCourseIdsFromPackage(CoursePageReqVO pageReqVO, Long packageId, boolean isInCourseIds) {
        CoursePackageDO coursePackageDO = coursePackageMapper.selectById(packageId);
        if (coursePackageDO == null || coursePackageDO.getCourseIds() == null || coursePackageDO.getCourseIds().isEmpty()) {
            return false;
        }
        if (isInCourseIds) {
            pageReqVO.setInCourseIds(coursePackageDO.getCourseIds());
        } else {
            pageReqVO.setNotInCourseIds(coursePackageDO.getCourseIds());
        }
        return true;
    }

    @Override
    public List<CourseDO> getAllCourseChapter(List<Long> ids) {
        return courseMapper.selectAllCourseChapter(ids);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCourseMaterial(CourseMaterialRltSaveReqVO createReqVO) {
        CourseDO updateObj = courseMapper.selectById(createReqVO.getCourseId());
        Set<Long> materialIds = Optional.ofNullable(updateObj.getCourseMaterialIds()).orElse(new HashSet<>());
        materialIds.addAll(createReqVO.getCourseMaterialIds());
        updateObj.setCourseMaterialIds(materialIds);
        courseMapper.updateById(updateObj);
        //插入关系表
        if (CollectionUtil.isNotEmpty(createReqVO.getCourseMaterialIds())) {
            courseMaterialRltMapper.insertBatch(convertList(createReqVO.getCourseMaterialIds(),
                    courseMaterialId -> new CourseMaterialRltDO().setCourseMaterialId(courseMaterialId).setCourseId(createReqVO.getCourseId())));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCourseMaterial(CourseMaterialRltSaveReqVO createReqVO) {
        CourseDO updateObj = courseMapper.selectById(createReqVO.getCourseId());
        Set<Long> materialIds = Optional.ofNullable(updateObj.getCourseMaterialIds()).orElse(new HashSet<>());
        materialIds.removeAll(createReqVO.getCourseMaterialIds());
        updateObj.setCourseMaterialIds(materialIds);
        courseMapper.updateById(updateObj);
        //删除关系表
        if (CollectionUtil.isNotEmpty(createReqVO.getCourseMaterialIds())) {
            for (Long courseMaterialId : createReqVO.getCourseMaterialIds()) {
                courseMaterialRltMapper.delete(new QueryWrapper<>(CourseMaterialRltDO.builder()
                        .courseId(createReqVO.getCourseId()).courseMaterialId(courseMaterialId).build()));
            }
        }
    }
}